package com.fhz.day014;

import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class MyIntentService2 extends IntentService {

    private static final String TAG = "feng";
    public MyIntentService2() {
        super("MyIntentService2");
    }

    @Override
    protected void onHandleIntent(Intent intent) {

        StringBuffer sb=new StringBuffer();
        HttpURLConnection connection=null;
        InputStream inputStream=null;
        try {
                URL url=new URL("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&page=1");
                connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(5*1000);
                connection.setConnectTimeout(5*1000);

                if(connection.getResponseCode()==200) {
                    inputStream = connection.getInputStream();
                    byte[] b = new byte[1024];
                    int len = 0;
                    while ((len = inputStream.read(b)) != -1) {
                        sb.append(new String(b, 0, len));
                    }
                    String s = sb.toString();
                    Log.i(TAG, "onHandleIntent: "+s);

                    //使用广播发送数据
                    Intent intent1 = new Intent();
                    intent1.setAction("com.feng");
                    Bundle bundle = new Bundle();
                    bundle.putString("json",s);
                    intent1.putExtras(bundle);
                    sendBroadcast(intent1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if(inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(connection!=null){
                    connection.disconnect();
                }
            }

    }


}